package com.xxxx.server.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxxx.server.pojo.MailConstants;
import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IMailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;

/**
 * Rabbitmq配置类
 */
@Configuration
public class RabbitMQConfig {
    //连接工厂
    @Resource
    private CachingConnectionFactory cachingConnectionFactory;

    @Resource
    private IMailLogService mailLogService;

    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQConfig.class);


    //向spring容器中注入RabbitTemplate对象，并配置开启确认消息回调和消息失败回调
    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        /**
         * 消息确认回调,确认消息是否到达broker
         * correlationData:消息唯一标识
         * ack：确认结果,消息是否发送成功
         * cause：失败原因
         */
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            String msgId = correlationData.getId();
            if (ack) {
                LOGGER.info("消息发送成功============>" + msgId);
                //监听消息是否发送成功，如果成功将状态改为1
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 1).eq("msgId", msgId));
            } else {
                LOGGER.error("消息发送到queue失败============>" + msgId);
            }
        });
        /**
         * 消息失败回调
         */
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                LOGGER.error("消息发送失败===========>" + message.getBody());
            }
        });
        return rabbitTemplate;
    }

    //〈绑定队列〉
    @Bean
    public Queue queue(){
        return new Queue(MailConstants.MAIL_QUEUE_NAME);
    }

    //〈绑定交换机〉
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME);
    }

    //〈绑定队列和路由键和交换机的关系〉
    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstants.MAIL_ROUTING_KEY_NAME);
    }
}
